import { Component, OnInit, forwardRef, ViewChild, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import { Http,Response } from '@angular/http';

import { CommonComponent } from '../../../../../core/common/common.component';
import { CommonService } from '../../../../../core/common/common.service';
import { ConfigService } from '../../../../../core/common/config.service';
import { TableDictService } from '../../../../../core/common/table-dict.service';
import { SelectComponent } from '../../../../../shared/component/ng2-select/select';
import { SelectItem } from '../../../../../shared/component/ng2-select/select-item';
@Component({
  selector: 'ncloud-nodecell-sdwan',
  templateUrl: './node-sdwan.component.html',
  styles: [``],
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NodeCellSDWANComponent), multi: true },
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => NodeCellSDWANComponent), multi: true }
  ]
})
export class NodeCellSDWANComponent extends CommonComponent implements OnInit {

  @ViewChild('nodeTypeSelect') nodeTypeSelect: SelectComponent;
  @ViewChild('nodeSubTypeSelect') nodeSubTypeSelect: SelectComponent;
  @ViewChild('bandWidthSelect') bandWidthSelect: SelectComponent;
  @ViewChild('province') province: SelectComponent;
  @ViewChild('city') city: SelectComponent;
  public provinces: Array<any> = [];
  @Output() public calculated: EventEmitter<any> = new EventEmitter();    
    public select: any = {};
  constructor(private common: CommonService, private http: Http, private tableDict: TableDictService, private config: ConfigService) {
    super();
  }
  writeValue(value) {
    super.writeValue(value);
    if (value) {
      //      放在这里主要是为了初始化省份，也可以在选择节点类型后去初始化
      this.initSelect();
    }
  }  
  private initSelect(): void {
    this.data.slaLevel = this.data.slaLevel ? this.data.slaLevel : '1';
    this.slaClicked(this.data.slaLevel);
    this.tableDict.get('BANDWIDTH').subscribe((data: any) => {
      this.select.bandwidth = data;
    });
    this.tableDict.get('ISP').subscribe((data: any) => {
      this.select.isp = data;
    });
    this.tableDict.get('ACCESS_TYPE').subscribe((data: any) => {
      this.select.wanAccessType = data;
    });
    this.tableDict.get('BILLING_CYCLE').subscribe((data: any) => {
      this.select.billingcycle = data;
    });
  }  
  ngOnInit() {
    super.ngOnInit();
  }
private initProvince(): void {
    this.tableDict.getProvince(this.data.slaLevel).subscribe((data: any) => {
      this.provinces = data;
    });
  }
  public slaClicked($event: any): void {
    this.data.slaLevel = $event;
    this.initProvince();
    this.getPaymoney();
  }
  public provinceSelected($event: any): void {
    this.tableDict.getCity(this.data.equip.province, this.data.slaLevel).subscribe((data: any) => {
      this.city.items = data;
      let exists = false;
      const active: any = this.city.active && this.city.active.length > 0 ? this.city.active[0] : {};
      this.city.itemObjects.forEach((i: SelectItem) => {
        if (i.id === active.id) {
          exists = true;
        }
      });
      if (!exists && this.city.itemObjects.length > 0) {
        this.city.active = [];
      }
    });
  }
  public citySelected($event: any): void {
  }
  public wanAccessTypeSelected($event: any): void {

  }
  public getPaymoney(): void {
    switch (this.data.discntType) {
      case '0':
        const controls = this.valForm.controls;
        if (controls['data.billingCycle'] && controls['data.billingCycle'].valid && controls['data.bandWidth']
          && controls['data.bandWidth'].valid &&controls['data.isp.wan.ispName'] && controls['data.isp.wan.ispName'].valid) {
          const url = this.config.get('url') + '?service=ProductService&method=getProdPriceInfo';
          const json = {
            discntId: this.data.discntId, bandWidth: this.data.bandWidth, nodeType: this.data.nodeType,
            ispName: this.data.isp.wan.ispName, slaLevel: this.data.slaLevel, billingCycle: this.data.billingCycle
          };
          this.http.post(url, json).toPromise().then((response: Response) => {
            const result = response.json();
            if (result && result.code === '0000') {
              this.data.standard = result.info.maxFee / 100;
              this.data.balance = result.info.minFee / 100;
              this.calculated.emit(this.data.standard);
            } else {
              this.data.standard = '';
              this.data.balance = '';
            }
          });
        }
        break;
      case '1':
        break;
      case '2':
        if (this.valForm.controls['data.billingCycle'].valid) {
          this.data.standard = this.data.maxFee * parseInt(this.data.billingCycle, 10) / 100;
          this.data.balance = this.data.minFee * parseInt(this.data.billingCycle, 10) / 100;
        }
        break;
    }
  }  
}
